<?php
/**
 * @author 段志岩
 * @date 2008.8.9
 * @summary 模型视图类
 */

class View extends Base{
	protected $tableName;
	protected $data;
	protected $db;
	protected $conditions;
	protected $sql;
	protected $limit;
	protected $where;

	public function __construct()
	{
		global $db;
		$this->db = $db;
		$this->sql = "";
		$this->limit = "";
	}
	public function __destruct()
	{
	}
	public function __get($property)
	{
		if(array_key_exists($property, $this->data))
		{
			return $this->data[$property];
		}
	}
	public function __set($property, $value)
	{
	}
	public function find()
	{
		$this->data = $this->db->query($this->toSql());

		return $this->data;
	}
	public function findOne()
	{
		$this->find();
		return $this->data[0];
	}
	public function add()
	{
		return false;
	}
	public function update()
	{
		return false;
	}
	public function delete()
	{
		return false;
	}
	public function setLimit($start, $end)
	{
		$start = (int) $start;
		$end = (int) $end;
		$this->limit = " " . $start . ", ". $end ." ";
	}
	/**
	 * 添加查询条件
	 *
	 * @param $field <string> 字段名称
	 * @param $op <string> 操作符 : =, >, >=, <=
	 * @param $value <string> 字段值
	 * @param $logic_op <string> 逻辑连接符，用于与后面的条件进行连接。
	 */
	public function addCondition($field, $op, $value, $logic_op)
	{
		$this->conditions[] = array("field" => $field, "op" => $op, "value" => $value, "link" => $logic_op);
	}
	/**
	 * 清空查询条件
	 */
	public function clearCondition()
	{
		$this->conditions = array();
	}
	public function clearData()
	{
		$this->data = array();
	}
	protected function _preParse()
	{}
	protected function _afterParse()
	{}
	/**
	 * 生成sql的where子句
	 */
	protected function parseWhere()
	{
		$this->where = " WHERE ";
		$this->_preParse();
		if(is_array($this->conditions)){
			foreach($this->conditions as $cond)
			{
				$this->where .= sprintf("`%s` %s '%s' %s ", $cond['field'], $cond['op'], $cond['value'], $cond['link']);
			}
		}else{
			$this->where .= "1";
		}
		$this->_afterParse();
		return $this->where .= " ";
	}
	public function toSql()
	{
		return $this->sql . $this->parseWhere();
	}
};
?>
